package com.ybkj.daijia.server.event.listener.errand;

import com.ybkj.daijia.PushDataV4;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.gexin.GeTuiEmployV4;
import com.ybkj.daijia.api.jpush.JiGuangEmployV4;
import com.ybkj.daijia.server.errand.Order;
import com.ybkj.daijia.server.event.model.errand.PaotuiOrderCreateEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandService;
import com.ybkj.daijia.server.service.OrderService;
import com.ybkj.daijia.server.service.ZhuancheService;
import com.ybkj.daijia.server.websocket.WebSocketSend;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

@Component
public class PaotuiOrderCreateEventListener implements ApplicationListener<PaotuiOrderCreateEvent> {

    private static final Logger logger = LoggerFactory
        .getLogger(PaotuiOrderCreateEventListener.class);

    @Autowired
    private CompanyService companyService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private ZhuancheService zhuanService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private ErrandService errandService;
    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Override
    @Async
    public void onApplicationEvent(PaotuiOrderCreateEvent event) {

        Order order = (Order) event.getSource();

        logger.debug("order paotui created event:{}", order.getOrderNo());
        Long orderId = order.getId();
        //推送数据到浏览器
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("orderId", order.getId());
        jsonObject.put("orderNo", order.getOrderNo());
        jsonObject.put("type", "paotuiNewOrders");
        Company mainCompany = companyService.getMain();
        WebSocketSend.boardcastToCompany(jsonObject, order.getCompanyId(), mainCompany.getId());
        Setting setting = settingUtils.get();
        if (setting.isAllowRushOrderErrand()) {
            Double rushOrderKm1 = setting.getRushOrderKm1();
            Double rushOrderKm2 = setting.getRushOrderKm2();
            Double rushOrderKm3 = setting.getRushOrderKm3();
            Integer rushOrderTime1 = setting.getRushOrderTime1();
            Integer rushOrderTime2 = setting.getRushOrderTime2();
            Integer rushOrderTime3 = setting.getRushOrderTime3();
            try {
                //第一阶段
                Thread.sleep(rushOrderTime1 * 1000);
                if (order.getStatus().equals(Order.ORDER_STATUS_NEW)) {
                    List<Driver> drivers = driverService
                        .errandListDrivers(order.getStartLng(), order.getStartLat(), rushOrderKm1);
                    if (!CollectionUtils.isEmpty(drivers)) {
                        for (Driver rushDriver : drivers) {
                            if (!rushDriver.getIsFreeze() && (
                                rushDriver.getStatus().equals(Driver.DRIVER_ONLINE) || rushDriver
                                    .getStatus().equals(Driver.DRIVER_APPLY_ORDER) || rushDriver
                                    .getStatus().equals(Driver.DRIVER_BUSY))) {
                                if (rushDriver.getDriverJobType().equals(Driver.DriverJobType.all)
                                    || rushDriver.getDriverJobType().toString()
                                    .contains(Driver.DriverJobType.paotui.toString())) {
                                    pushNewOrder(order, rushDriver, setting);
                                }
                            }
                        }
                    }

                    //第二阶段
                    Thread.sleep(rushOrderTime2 * 1000);
                    order = errandService.findOne(orderId);
                    if (order.getStatus().equals(Order.ORDER_STATUS_NEW)) {

                        drivers = driverService
                            .errandListDrivers(order.getStartLng(), order.getStartLat(),
                                rushOrderKm2);
                        if (!CollectionUtils.isEmpty(drivers)) {
                            for (Driver rushDriver : drivers) {
                                if (!rushDriver.getIsFreeze() && (
                                    rushDriver.getStatus().equals(Driver.DRIVER_ONLINE)
                                        || rushDriver.getStatus().equals(Driver.DRIVER_APPLY_ORDER)
                                        || rushDriver.getStatus().equals(Driver.DRIVER_BUSY))) {
                                    if (rushDriver.getDriverJobType()
                                        .equals(Driver.DriverJobType.all) || rushDriver
                                        .getDriverJobType().toString()
                                        .contains(Driver.DriverJobType.paotui.toString())) {
                                        pushNewOrder(order, rushDriver, setting);
                                    }
                                }
                            }
                        }

                        //第三阶段
                        Thread.sleep(rushOrderTime3 * 1000);
                        order = errandService.findOne(orderId);
                        if (order.getStatus().equals(Order.ORDER_STATUS_NEW)) {
                            drivers = driverService
                                .errandListDrivers(order.getStartLng(), order.getStartLat(),
                                    rushOrderKm3);
                            if (!CollectionUtils.isEmpty(drivers)) {
                                for (Driver rushDriver : drivers) {
                                    if (!rushDriver.getIsFreeze() && (
                                        rushDriver.getStatus().equals(Driver.DRIVER_ONLINE)
                                            || rushDriver.getStatus()
                                            .equals(Driver.DRIVER_APPLY_ORDER) || rushDriver
                                            .getStatus().equals(Driver.DRIVER_BUSY))) {
                                        if (rushDriver.getDriverJobType()
                                            .equals(Driver.DriverJobType.all) || rushDriver
                                            .getDriverJobType().toString()
                                            .contains(Driver.DriverJobType.paotui.toString())) {
                                            pushNewOrder(order, rushDriver, setting);
                                        }
                                    }
                                }
                            }
                        }

                    }

                }


            } catch (Exception e) {
                e.printStackTrace();
                logger.debug("push error : " + e.getMessage());
            }
        }
    }

    private void pushNewOrder(Order newOrder, Driver rushDriver, Setting setting) {
        try {
            //发送设备推送
            PushDataV4 pushDataV4 = new PushDataV4();
            pushDataV4.setCode("0X02");
            pushDataV4.setData(newOrder.getId());
            pushDataV4.setType("0X02");
            pushDataV4.setSound("beep_2");
            Map<String, String> extra = new HashMap<String, String>();
            extra.put("content", "又有新工单可以抢啦");
            pushDataV4.setExtra(extra);

            boolean getuiOnline = false;
            if (StringUtils.isNotBlank(rushDriver.getUserID())) {
                getuiOnline = GeTuiEmployV4
                    .getClientOnline(rushDriver.getUserID(), settingUtils.get());
            }

            if (getuiOnline) {
                if (rushDriver.getDetailedJobType()
                    .contains(newOrder.getOrderTypeId().toString())) {
                    GeTuiEmployV4.push(rushDriver, pushDataV4, setting);
                }
            } else {
                if (StringUtils.isNotBlank(rushDriver.getRegistrationId()) && rushDriver
                    .getDetailedJobType().contains(newOrder.getOrderTypeId().toString())) {
                    JiGuangEmployV4.push(rushDriver, pushDataV4, setting);
                }
            }

        } catch (Exception e) {
            logger.debug("push error : " + e.getMessage());
        }
    }

    public Boolean getDriverBusy(Long employId) {
        if (employId != null) {
            try {
                Long zhuancheAmount = zhuanService.countActivedOrdersByDriver(employId);
                if (zhuancheAmount > 0) {
                    return true;
                }
                Long daijiaAmount = orderService.countActivedOrdersByDriver(employId);
                if (daijiaAmount > 0) {
                    return true;
                }
                Long paotuiAmount = errandService.countBusyAmount(employId);
                Setting setting = settingUtils.get();
                Integer errandGrabAmount = setting.getErrandGrabAmount();

                if (errandGrabAmount != 0 && paotuiAmount >= errandGrabAmount) {
                    return true;
                }
                return false;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } else {
            return null;
        }
    }
}
